package thread;
import java.util.*;
/**
 * 并发安全的集合API:
 * ArrayList、LinkedList、HashSet都不是并发安全的(异步)
 */
public class SyncDemo4 {
    public static void main(String[] args) {
        //List<Integer> sb = new ArrayList<>();
        //List<Integer> sb = new LinkedList<>();
        //Set<Integer> sb = new HashSet<>();

        //List<Integer> sb = Collections.synchronizedList(new ArrayList<>());
        //List<Integer> sb = Collections.synchronizedList(new LinkedList<>());
        Set<Integer> sb = Collections.synchronizedSet(new HashSet<>());
        Thread t1 = new Thread() {
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    sb.add(i);
                }
            }
        };
        Thread t2 = new Thread() {
            public void run() {
                for (int i = 1000; i < 2000; i++) {
                    sb.add(i);
                }
            }
        };
        t1.start();
        t2.start();
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
        }
        System.out.println(sb.size());  //2000
        System.out.println(sb);
    }
}
